package cn.edu.nju.software.greencreditsystem.business;

import cn.edu.nju.software.greencreditsystem.DAO.*;
import cn.edu.nju.software.greencreditsystem.domain.*;
import cn.edu.nju.software.greencreditsystem.factory.DAOFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Date;

/**
 * 作者：何启睿
 * 创建时间：2011-8-20
 * 类描述：处理通过审核的环境报表的静态工具类
 */
public class EnvironmentHandler
{
    /**
     * 方法描述：传入已审核的环境报表，分析后生成环境评分、指标、警告记录存入数据库
     * param：xml文件，EnvironmentExcel对象，企业
     * return：是否成功
    */
    public static boolean handle(String xmlPath, EnvironmentExcel ee, int enterpriseID)
    {
        boolean result = false;
        
        String excelPath = "temp" + System.currentTimeMillis() + ".xls";
        File excelFile = new File(excelPath);
        EnvironmentAnalyser analyser = new CoinEnvironmentAnalyser();
        EnterpriseDAO edao = DAOFactory.getEnterpriseDAOInstance();
        EnvironmentFactorDAO efdao = DAOFactory.getEnvironmentFactorDAOInstance();
        EnvironmentIndexDAO eidao = DAOFactory.getEnvironmentIndexDAOInstance();
        EnvironmentScoreDAO esdao = DAOFactory.getEnvironmentScoreDAOInstance();
        EnvironmentStandardValueDAO esvdao = DAOFactory.getEnvironmentStandardValueDAOInstance();
        EnvironmentWarningDAO ewdao = DAOFactory.getEnvironmentWarningDAOInstance();
        EnvironmentWarningTypeDAO ewtdao = DAOFactory.getEnvironmentWarningTypeDAOInstance();
        FinancialScoreDAO fsdao = DAOFactory.getFinancialScoreDAOInstance();
        SystemConstantDAO scdao= DAOFactory.getSystemConstantDAOInstance();
        WarningTemplateDAO wtdao = DAOFactory.getWarningTemplateDAOInstance();
        Date today = ee.getSubmitDate();
        
        try
        {
            FileOutputStream out = new FileOutputStream(excelFile);
            out.write(ee.getData());
            out.flush();
            out.close();
            
            double scoreAndIndex[] = analyser.getIndex(excelPath, xmlPath);
            for(int i = 0; i < 6; i++)
            {
                EnvironmentFactor eftemp = efdao.getByName(CoinEnvironmentAnalyser.indexNames[i]);
                EnvironmentStandardValue standardValue = esvdao.get(enterpriseID, eftemp.getId()); 
                
                //若数值等于0，则认为此指标或评分不存在，不保存记录
                if(scoreAndIndex[i] == 0)
                    continue;
                
                //保存环境评分
                EnvironmentScore es = new EnvironmentScore();
                es.setDate(ee.getDeadline());
                es.setEnterprise(edao.getById(enterpriseID));
                es.setFactor(eftemp);
                es.setValue(scoreAndIndex[i]);
                esdao.save(es);
                
                //若大于标准值/小于标准值/距标准值过远则添加警告
                if((standardValue.getType() == -1 && standardValue.getStandardValue() < es.getValue())
                        || (standardValue.getType() == 0 && standardValue.getStandardValue() > es.getValue())
                        || ( standardValue.getType() > 0 && Math.abs(standardValue.getStandardValue() - es.getValue()) > standardValue.getType()))
                {
                    EnvironmentWarning ew = new EnvironmentWarning();
                    EnvironmentWarningType ewt = new EnvironmentWarningType();
                    
                    ewt.setFactor(eftemp);
                    ewt.setType(EnvironmentWarningType.STANDARD);
                    ewt.setValue(scoreAndIndex[i]);
                    
                    ew.setBankReaded(false);
                    ew.setDate(today);
                    ew.setEnterprise(edao.getById(enterpriseID));
                    ew.setEnterpriseReaded(false);
                    ew.setType(ewt);
                    ew.setWarningTemplate(wtdao.getById((int) scdao.get("currentWarningTemplate")));
                    
                    ewtdao.save(ewt);
                    ewdao.save(ew);
                }
                //若变动幅大于最大允许变动幅则生成警告
                else if(esdao.getIncreaseMargin(enterpriseID, eftemp.getId()) > standardValue.getChangeValue())
                {
                    EnvironmentWarning ew = new EnvironmentWarning();
                    EnvironmentWarningType ewt = new EnvironmentWarningType();
                    
                    ewt.setFactor(eftemp);
                    ewt.setType(EnvironmentWarningType.CHANGE);
                    ewt.setValue(scoreAndIndex[i]);
                    
                    ew.setBankReaded(false);
                    ew.setDate(today);
                    ew.setEnterprise(edao.getById(enterpriseID));
                    ew.setEnterpriseReaded(false);
                    ew.setType(ewt);
                    ew.setWarningTemplate(wtdao.getById((int) scdao.get("currentWarningTemplate")));
                    
                    ewtdao.save(ewt);
                    ewdao.save(ew);
                }
            }
            for(int i = 6; i < CoinEnvironmentAnalyser.indexNames.length; i++)
            {
                EnvironmentFactor eftemp = efdao.getByName(CoinEnvironmentAnalyser.indexNames[i]);
                EnvironmentStandardValue standardValue = esvdao.get(enterpriseID, eftemp.getId()); 
                
                //若数值等于0，则认为此指标或评分不存在，不保存记录
                if(scoreAndIndex[i] == 0)
                    continue;
                
                //保存环境指标
                EnvironmentIndex ei = new EnvironmentIndex();
                ei.setDate(ee.getDeadline());
                ei.setEnterprise(edao.getById(enterpriseID));
                ei.setFactor(eftemp);
                ei.setValue(scoreAndIndex[i]);
                eidao.save(ei);
                
                //若大于标准值/小于标准值/距标准值过远则添加警告
                if((standardValue.getType() == -1 && standardValue.getStandardValue() < ei.getValue())
                        || (standardValue.getType() == 0 && standardValue.getStandardValue() > ei.getValue())
                        || ( standardValue.getType() > 0 && Math.abs(standardValue.getStandardValue() - ei.getValue()) > standardValue.getType()))
                {
                    EnvironmentWarning ew = new EnvironmentWarning();
                    EnvironmentWarningType ewt = new EnvironmentWarningType();
                    
                    ewt.setFactor(eftemp);
                    ewt.setType(EnvironmentWarningType.STANDARD);
                    ewt.setValue(scoreAndIndex[i]);
                    
                    ew.setBankReaded(false);
                    ew.setDate(today);
                    ew.setEnterprise(edao.getById(enterpriseID));
                    ew.setEnterpriseReaded(false);
                    ew.setType(ewt);
                    ew.setWarningTemplate(wtdao.getById((int) scdao.get("currentWarningTemplate")));
                    
                    ewtdao.save(ewt);
                    ewdao.save(ew);
                }
                //若变动幅大于最大允许变动幅则生成警告
                else if(esdao.getIncreaseMargin(enterpriseID, eftemp.getId()) > standardValue.getChangeValue())
                {
                    EnvironmentWarning ew = new EnvironmentWarning();
                    EnvironmentWarningType ewt = new EnvironmentWarningType();
                    
                    ewt.setFactor(eftemp);
                    ewt.setType(EnvironmentWarningType.CHANGE);
                    ewt.setValue(scoreAndIndex[i]);
                    
                    ew.setBankReaded(false);
                    ew.setDate(today);
                    ew.setEnterprise(edao.getById(enterpriseID));
                    ew.setEnterpriseReaded(false);
                    ew.setType(ewt);
                    ew.setWarningTemplate(wtdao.getById((int) scdao.get("currentWarningTemplate")));
                    
                    ewtdao.save(ewt);
                    ewdao.save(ew);
                }
            }
            
            //更新企业等级评定
            Enterprise e = edao.getById(enterpriseID);
            double score = ((fsdao.getLatestTotalScore(enterpriseID) * scdao.get("financialWeight"))
                            + (esdao.getLatestTotalScore(enterpriseID) * scdao.get("environmentWeight"))) / 100;
            if(score < scdao.get("oneStar"))
                e.setLevel(1);
            else if(score < scdao.get("twoStar"))
                e.setLevel(2);
            else if(score < scdao.get("threeStar"))
                e.setLevel(3);
            else if(score < scdao.get("fourStar"))
                e.setLevel(4);
            else
                e.setLevel(5);
            edao.update(e);
            
            result = true;
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }finally
        {
            excelFile.delete();
        }
        
        return result;
    }
}
